<!--
 * @Description: 计划申购记录
 *
 * @Author: guichengcai<guichengcai>
 * @Date: 2023-07-03 17:11:54
 * @FilePath: /yuxiuproweb/src/views/reportforms/sale/index.vue
-->
<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
      class="queryForm"
    >
      <el-form-item label="采购ID" prop="purchaseOrderId">
        <el-input
          v-model="queryParams.purchaseOrderId"
          placeholder="请输入采购ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采购单号" prop="orderNumber">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入采购单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      
      <el-form-item label="供应商" prop="supplier">
        <el-select
          v-model="queryParams.supplier"
          placeholder="请选择供应商名称"
          style="width: 100%"
          clearable
          filterable
          remote
          reserve-keyword
          :remote-method="getSupplierData"
        >
          <el-option
            v-for="item in supplierData"
            :key="item.vendorId"
            :label="item.vendorName"
            :value="item.vendorName"
          >
            <span style="padding-left: 6px">{{ item.vendorName }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="供应商型号" prop="vendorModel" label-width="86px">
        <el-input
          v-model="queryParams.vendorModel"
          placeholder="请输入供应商型号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="型号" prop="modelNumber">
        <el-input
          v-model="queryParams.modelNumber"
          placeholder="请输入型号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="提交时间" prop="createDate">
        <el-date-picker
          align="center"
          style="width: 240px"
          v-model="createDateObj"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          :default-time="['00:00:00', '23:59:59']"
          format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="采购审核" prop="buysumbitTimeObj">
        <el-date-picker
          align="center"
          style="width: 240px"
          v-model="buysumbitTimeObj"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="财务审核" prop="financialBuysumbitTimeObj">
        <el-date-picker
          align="center"
          style="width: 240px"
          v-model="financialBuysumbitTimeObj"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          @click="sumbitapply(0)"
          v-hasRole="['money']"
          >财务审核</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['pro:record:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="recordList"
      @selection-change="handleSelectionChange"
      :max-height="maxHeight"
      :row-style="{ height: '20px' }"
      :cell-style="{ padding: '4px 0' }"
      border
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
        fixed="left"
      />
      <el-table-column
        label="采购ID"
        align="center"
        prop="purchaseOrderId"
        fixed="left"
      />
      <el-table-column
        label="采购单号"
        align="center"
        prop="orderNumber"
        width="120px"
        fixed="left"
      >
        <template slot-scope="scope">
          <el-button
            size="default"
            type="text"
            @click="handlechange(scope.row)"
            v-hasPermi="['pro:record:edit']"
            style="font-weight: bold"
            >{{ scope.row.orderNumber }}</el-button
          >
        </template>
      </el-table-column>
      <!-- 采购 -->
      <el-table-column
        label="采购审核时间"
        align="center"
        width="150"
        prop="buysumbitTime"
        sortable
      >
        <template slot-scope="scope">
          <div>
            {{ scope.row.buysumbitTime | dateFormat }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="财务审核时间"
        align="center"
        width="150"
        prop="financialBuysumbitTime"
        sortable
      >
        <template slot-scope="scope">
          <div>
            {{ scope.row.financialBuysumbitTime | dateFormat }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="提交时间"
        align="center"
        width="120"
        prop="submissionTime"
        sortable
      />
      <el-table-column label="申购类型" align="center" prop="subscriptionType">
        <template slot-scope="scope">
          <span
            class="textunderline"
            v-if="scope.row.subscriptionType == 0"
            @click="openTaskOrder(scope.row, 'lc')"
            >零裁</span
          >
          <span v-if="scope.row.subscriptionType == 2">库存</span>
          <span
            class="textunderline"
            v-if="scope.row.subscriptionType == 1"
            @click="openTaskOrder(scope.row, 'ql')"
            >欠料</span
          >
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        align="center"
        width="120"
        prop="itemStatus"
      >
        <template slot-scope="scope">
         
          <span v-if="scope.row.itemStatus == 1">待财务审核</span>
         
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="存货编码"
        align="center"
        prop="codeNumber"
        width="120"
      /> -->
      <el-table-column
        label="供应商"
        align="center"
        width="120"
        prop="supplier"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="供应商型号"
        align="center"
        prop="vendorModel"
        width="120"
      />
      <el-table-column
        label="型号"
        align="center"
        prop="modelNumber"
        width="120"
      >
        <template slot-scope="scope">
          <div>
            <span class="textunderline" @click="opentableInventory(scope.row)">
              {{ scope.row.modelNumber }}
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="门幅" align="center" prop="fabricWidth" />
      <el-table-column
        label="备注"
        align="center"
        width="120"
        prop="itemRemark"
        :show-overflow-tooltip="true"
      />

      <!-- <el-table-column label="客户" align="center" prop="subtotal" /> -->
      <!-- <el-table-column
        label="工单号"
        align="center"
        prop="purchaseOrderItemId"
      /> -->
      <el-table-column label="申购量" align="center" prop="quantity" />
      <el-table-column
        label="申购确认量"
        align="center"
        prop="confirmQuantity"
        width="120"
      />
      <el-table-column
        label="计划到货日期"
        width="120"
        align="center"
        prop="plannedDeliveryDate"
      />
      <el-table-column
        label="供应商到货日期"
        width="120"
        align="center"
        prop="supplierArrivalDate"
      />

      <!-- <el-table-column label="生成订单" align="center" prop="subtotal" /> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        min-width="120px"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handlechange(scope.row)"
            v-hasPermi="['pro:record:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handledelete(scope.row)"
            style="color: #f56c6c"
            v-hasPermi="['pro:record:delete']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增零裁 查询生产任务单面料状态isShortage为0零裁-->
    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="openlc"
      width="1000px"
      append-to-body
      style="margin: auto 30px"
    >
      <el-table
        v-loading="loading"
        :data="recordListlc"
        @selection-change="handleSelectionChangelc"
        :max-height="maxHeight"
      >
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="工单号" align="center" prop="workOrderNumber" /> -->
        <!-- <el-table-column label="存货编码" align="center" prop="number">
          <template slot-scope="scope">
            {{ scope.row.number }}
          </template>
        </el-table-column> -->
        <el-table-column label="客户" align="center" prop="clientName" />
        <el-table-column label="型号" align="center" prop="modelNumber" />
        <el-table-column label="长度" align="center" prop="length" />
        <el-table-column label="申请量" align="center" prop="applynumber">
          <!-- <template slot-scope="scope">
            <el-input v-model="scope.row.applynumber"></el-input>
          </template> -->
        </el-table-column>
        <el-table-column label="计划到货日期" min-width="100" prop="applytime">
          <template slot-scope="scope">
            <el-date-picker
              v-model="scope.row.applytime"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions"
              style="width: 100%"
            ></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="备注" min-width="120" prop="applybz">
          <template slot-scope="scope">
            <el-input v-model="scope.row.applybz"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormlc">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 新增欠料 查询生产任务单面料状态isShortage为1欠料-->
    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="openql"
      width="1000px"
      append-to-body
      style="margin: auto 30px"
    >
      <el-table
        v-loading="loading"
        :data="recordListql"
        @selection-change="handleSelectionChangelc"
        :max-height="maxHeight"
      >
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="工单号" align="center" prop="workOrderNumber" /> -->
        <!-- <el-table-column label="存货编码" align="center" prop="number" /> -->

        <el-table-column label="型号" align="center" prop="modelNumber">
          <template slot-scope="scope">
            <div>
              <el-popover
                trigger="click"
                :ref="'qlPopover-' + scope.$index"
                title="库存信息"
              >
                <selInventory
                  v-if="qlPopover == scope.$index"
                  ref="qbInventory"
                  :multi="-1"
                  style="width: 640px"
                ></selInventory>
                <div
                  slot="reference"
                  class="textunderline"
                  @click="openInventory(scope.row, scope.$index, 'qlPopover')"
                >
                  {{ scope.row.modelNumber }}
                </div>
              </el-popover>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="长度" align="center" prop="length" />
        <el-table-column label="申请量" min-width="120" prop="applynumber">
          <template slot-scope="scope">
            <el-input v-model="scope.row.applynumber"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="计划到货日期" min-width="120" prop="applytime">
          <template slot-scope="scope">
            <el-date-picker
              v-model="scope.row.applytime"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions"
              style="width: 100%"
            ></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="备注" min-width="120" prop="applybz">
          <template slot-scope="scope">
            <el-input v-model="scope.row.applybz"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormql">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 新增库存 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="openkc"
      append-to-body
      style="margin: auto 0px"
      width="1200px"
    >
      <div style="display: flex; align-items: center">
        <el-input
          placeholder="请输入型号"
          v-model="kcParams.name"
          style="width: 200px"
          size="small"
          clearable
          @keyup.enter.native="search()"
        >
        </el-input>
        <el-button
          class="filter-item"
          type="primary"
          size="small"
          @click="search()"
        >
          查询
        </el-button>
      </div>
      <el-form
        ref="formaddkc"
        :model="formData"
        :rules="ruleskc"
        label-width="100px"
      >
        <el-table
          v-loading="loading"
          :data="formData.recordListkc"
          @selection-change="handleSelectionChangekc"
          :max-height="maxHeight"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="存货编码" width="120" prop="number" />
          <el-table-column label="型号" width="120" prop="name">
            <template slot-scope="scope">
              <div>
                <el-popover
                  trigger="click"
                  :ref="'kcPopover-' + scope.$index"
                  title="库存信息"
                >
                  <selInventory
                    v-if="kcPopover == scope.$index"
                    ref="kcInventory"
                    :multi="-1"
                    style="width: 640px"
                  ></selInventory>
                  <span
                    slot="reference"
                    class="textunderline"
                    @click="openInventory(scope.row, scope.$index, 'kcPopover')"
                    >{{ scope.row.name }}</span
                  >
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="门幅" width="120" prop="doorwidth" />
          <el-table-column
            label="安全库存量"
            width="100"
            prop="safetyInventory"
          />
          <el-table-column
            label="仓库现存量"
            width="100"
            prop="inventoryQuantity"
          />
          <el-table-column label="申请量" prop="applynumber" min-width="100">
            <template slot-scope="scope">
              <el-form-item
                :prop="'recordListkc.' + scope.$index + '.applynumber'"
                :rules="ruleskc.applynumber"
              >
                <el-input v-model="scope.row.applynumber"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="计划到货日期"
            min-width="120"
            prop="applytime"
          >
            <template slot-scope="scope">
              <el-form-item
                :prop="'recordListkc.' + scope.$index + '.applytime'"
                :rules="ruleskc.applytime"
              >
                <el-date-picker
                  v-model="scope.row.applytime"
                  value-format="yyyy-MM-dd"
                  :picker-options="pickerOptions"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="100" prop="applybz">
            <template slot-scope="scope">
              <el-form-item :prop="'recordListkc.' + scope.$index + '.applybz'">
                <el-input v-model="scope.row.applybz"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <!-- <el-table-column label="状态" width="120" prop="subtotal" /> -->
        </el-table>
        <pagination
          v-show="totalkc > 0"
          :total="totalkc"
          :page.sync="kcParams.pageNum"
          :limit.sync="kcParams.pageSize"
          @pagination="search"
        />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormaddkc">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 处理订单 -->
    <el-dialog
      :close-on-click-modal="false"
      title="处理订单"
      :visible.sync="opens"
      width="90vw"
      append-to-body
    >
      <el-form label-width="100px">
        <el-table
          v-loading="loading"
          :data="applylist"
          @selection-change="handleSelectionChangekc"
          :max-height="maxHeight"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="存货编码" width="120" prop="codeNumber">
          </el-table-column>
          <el-table-column label="型号" width="120" prop="modelNumber" />
          <el-table-column label="门幅" width="100" prop="fabricWidth" />
          <!-- <el-table-column
            label="安全库存量"
            width="100"
            prop="safetyInventory"
          />
          <el-table-column
            label="仓库现存量"
            width="100"
            prop="availableQuantity"
          /> -->
          <el-table-column label="申请量" width="150" prop="quantity">
            <template slot-scope="scope">
              <el-form-item
                :prop="'recordListkc.' + scope.$index + '.quantity'"
              >
                <el-input v-model="scope.row.quantity"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="申请确认量"
            width="150"
            prop="confirmQuantity"
          >
            <template slot-scope="scope">
              <el-form-item
                :prop="'recordListkc.' + scope.$index + '.confirmQuantity'"
              >
                <el-input v-model="scope.row.confirmQuantity"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="计划到货日期"
            width="160"
            prop="plannedDeliveryDate"
          >
            <template slot-scope="scope">
              <el-form-item
                :prop="'recordListkc.' + scope.$index + '.plannedDeliveryDate'"
              >
                <el-date-picker
                  v-model="scope.row.plannedDeliveryDate"
                  value-format="yyyy-MM-dd"
                  :picker-options="pickerOptions"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="供应商到货日期"
            width="160"
            prop="supplierArrivalDate"
          >
            <template slot-scope="scope">
              <el-form-item
                :prop="'recordListkc.' + scope.$index + '.supplierArrivalDate'"
              >
                <el-date-picker
                  v-model="scope.row.supplierArrivalDate"
                  value-format="yyyy-MM-dd"
                  :picker-options="pickerOptions"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="供应商" width="150" prop="supplier">
            <template slot-scope="scope">
              <el-form-item
                :prop="'recordListkc.' + scope.$index + '.supplier'"
              >
                <!-- <el-input v-model="scope.row.supplier"></el-input> -->
                <el-select
                  v-model="scope.row.supplier"
                  placeholder="供应商"
                  size="small"
                  style="width: 100%"
                  clearable
                  @change="changeSupplier"
                  filterable
                  remote
                  reserve-keyword
                  :remote-method="getSupplierData"
                >
                  <el-option
                    v-for="item in supplierData"
                    :key="item.vendorId"
                    :label="item.vendorName"
                    :value="item.vendorName"
                  >
                    <!-- <span style="float: left">{{ item.vendorCode }} </span> -->
                    <span style="padding-left: 6px">{{ item.vendorName }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="itemRemark">
            <template slot-scope="scope">
              <el-form-item
                :prop="'recordListkc.' + scope.$index + '.itemRemark'"
              >
                <el-input v-model="scope.row.itemRemark"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpdate">确 定</el-button>
        <el-button @click="cancels">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      title="库存信息"
      :visible.sync="tablePopover"
      width="70vw"
      append-to-body
    >
      <selInventory ref="tableInventory" :multi="2"></selInventory>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      title="工单信息"
      :visible.sync="tableTaskOrder"
      width="72vw"
      append-to-body
    >
      <selTaskOrder
        v-if="tableTaskType == 'lc'"
        ref="TaskOrder"
        :multi="2"
        :showSearch="false"
      ></selTaskOrder>
      <selQLTaskOrder
        v-if="tableTaskType == 'ql'"
        ref="QLTaskOrder"
        :multi="2"
        :showSearch="false"
        :searchVal="searchVal"
      ></selQLTaskOrder>
    </el-dialog>
    <!-- 客服提交 -->
    <el-dialog
      :title="'客服提交'"
      :append-to-body="true"
      width="400px"
      :visible.sync="scheduleVisible"
      :close-on-click-modal="false"
      class="paichengDialog"
    >
      <div style="display: flex">
        <el-date-picker
          style="width: 100%; margin-right: 10px; flex: 1"
          v-model="plandate"
          type="date"
          placeholder="YYYY-MM-DD"
        ></el-date-picker>
        <!-- :picker-options="pickerOptions" -->
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="submitSchedule()"
          >确 定</el-button
        >
        <el-button size="small" @click="scheduleVisible = false"
          >取 消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
///dev-api/qb/purchaseOrderController/list
import {
  listRecord,
  getlistlc,
  getlistql,
  getlistkc,
  addkc,
  updatekc,
  deletekc,
  sumbitapply,
  sumbitapplys,
  getapplylist,
  getapplylistitem,
} from "@/api/buys/qbbuyapply";
import { listVendor } from "@/api/mes/md/vendor";
import commonMix from "@/utils/mixins/common";
import { listInventory } from "@/api/material/inventory";
import selInventory from "@/views/material/inventory/mods/selTable.vue";
import selTaskOrder from "@/views/qb/qb/mods/selectItem.vue";
import selQLTaskOrder from "@/views/qb/qb/mods/select.vue";
export default {
  mixins: [commonMix],
  name: "Record",
  components: { selInventory, selTaskOrder, selQLTaskOrder },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      selRow: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      opens: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      totallc: 0,
      totalql: 0,
      totalkc: 0,
      // 交易记录表格数据
      recordList: [],
      applylist: [],
      // 零裁数据
      recordListlc: [],
      // 欠料数据
      recordListql: [],
      // 库存数据

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      openlc: false,
      openql: false,
      openkc: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        purchaseOrderId: null,
        supplier: null,
        modelNumber: null,
        vendorModel: null,
        itemStatus: 1,
        orderNumber: null,
      },
      kcParams: {
        pageNum: 1,
        pageSize: 100,
        type: 2,
        isStockUp: 1,
        isbuy: 1,
        name: "",
      },
      createDateObj: [], //
      buysumbitTimeObj: [], //
      financialBuysumbitTimeObj: [], //this.getCreateDateTime()
      brandList: [],
      // 表单参数
      form: {},

      formaddkc: {},
      formaddlc: {},
      formData: {
        recordListkc: [],
      },
      formaddql: {},
      // 表单校验
      rules: {},
      ruleskc: {
        applynumber: [
          { required: true, message: "请输入申购量", trigger: "blur" },
        ],
        applytime: [
          { required: true, message: "请输入到货时间", trigger: "blur" },
        ],
      },
      multipleSelection: [],
      verify: [],
      // 禁用今天以前的日期
      pickerOptions: {
        disabledDate(v) {
          return v.getTime() < new Date().getTime() - 86400000; //  - 86400000是否包括当天
        },
      },
      supplierData: [], //获取供应商信息
      tablePopover: false,
      kcPopover: -1,
      qlPopover: -1,
      scheduleVisible: false,
      plandate: null,
      tableTaskOrder: false,
      tableTaskType: "",
      searchVal: "",
    };
  },
  created() {
    this.getList();
    this.getSupplierData();
  },
  methods: {
    handlechange(row) {
      this.reset();
      this.opens = true;
      getapplylistitem(row.purchaseOrderItemId).then((response) => {
        this.applylist = [];
        this.applylist.push(response.data);
        // this.total = response.total;
        // this.loading = false;
      });
    },
    // 确认修改
    submitUpdate() {
      updatekc(this.applylist[0]).then((res) => {
        this.$modal.msgSuccess(res.msg || "修改成功");
        this.opens = false;
        this.getList();
      });
    },
    handleSelectionChangelc(val) {
      this.multipleSelection = val; //零裁 勾选
    },
    // 确认新增-零裁
    submitFormlc() {
      if (this.multipleSelection.length > 0) {
        var paramItemArr = [];
        for (var i = 0; i < this.multipleSelection.length; i++) {
          var item = this.multipleSelection[i];
          console.log(item);
          var obj = {
            codeNumber: item.codeNumber, //存货编码
            quantity: item.applynumber, //申请数量
            plannedDeliveryDate: item.applytime, //计划到货日期
            itemRemark: item.applybz, //备注
            modelNumber: item.modelNumber, //型号
            fabricWidth: item.fabricWidth, //门幅
            productionTaskId: item.productionTaskId,
            type: 2, //子表类型1窗帘2墙布
          };
          paramItemArr.push(obj);
        }
        const paramslc = {
          items: paramItemArr,
          subscriptionType: 0, //申购类型 零裁
          type: 2, //主表类型1窗帘
        };
        console.log(paramslc);
        // return;
        addkc(paramslc).then((res) => {
          this.$modal.msgSuccess(res.msg || "新增成功");
          this.openlc = false;
          this.getList();
        });
      } else {
        this.$message.error("请勾选数据");
      }
    },
    // 确认新增-欠料
    submitFormql() {
      if (this.multipleSelection.length > 0) {
        var paramItemArr = [];
        for (var i = 0; i < this.multipleSelection.length; i++) {
          var item = this.multipleSelection[i];
          var obj = {
            codeNumber: item.codeNumber, //存货编码
            quantity: item.applynumber, //申请数量
            plannedDeliveryDate: item.applytime, //计划到货日期
            itemRemark: item.applybz, //备注
            modelNumber: item.modelNumber, //型号
            fabricWidth: item.fabricWidth, //门幅
            type: 2, //子表类型1窗帘
          };
          paramItemArr.push(obj);
        }
        const paramskc = {
          items: paramItemArr,
          subscriptionType: 1, //申购类型 欠料
          type: 2, //主表类型1窗帘
        };
        addkc(paramskc).then((res) => {
          this.$modal.msgSuccess(res.msg || "新增成功");
          this.openlc = false;
          this.getList();
        });
      } else {
        this.$message.error("请勾选数据");
      }
    },
    // 新增库存
    async submitFormaddkc(row) {
      if (this.multipleSelection.length > 0) {
        console.log("save!", this.multipleSelection);
        var paramItemArr = [];
        for (var i = 0; i < this.multipleSelection.length; i++) {
          var item = this.multipleSelection[i];
          var obj = {
            codeNumber: item.number, //存货编码
            quantity: item.applynumber, //申请数量
            plannedDeliveryDate: item.applytime, //计划到货日期
            itemRemark: item.applybz, //备注
            modelNumber: item.name, //型号
            fabricWidth: item.doorwidth, //门幅
            supplier: item.vendorName, //供应商名称
            supplierId: item.vendorId, //供应商id
            vendorModel: item.vendorModel,
            type: 2, //子表类型 2墙布
          };
          paramItemArr.push(obj);
        }
        const paramskc = {
          items: paramItemArr,
          subscriptionType: 2,
          type: 2, //主表类型 2墙布
        };
        addkc(paramskc).then((res) => {
          this.$modal.msgSuccess("新增成功");
          this.openkc = false;
          this.getList();
        });
      } else {
        console.log("请勾选数据");
        this.$message.error("请勾选数据");
      }
    },
    cancels() {
      this.opens = false;
      this.reset();
    },

    handleSelectionChangekc(val) {
      this.multipleSelection = val;
      console.log(val);
      // 获取表单所有要校验的字段
      const prop = this.$refs.formaddkc.fields.map((item) => item.prop);
      if (val.length <= 0) return this.$refs.formaddkc.clearValidate(prop);
      this.verify = [];
      // 将选中的数据和全部表格中校验的字段遍历 取出勾选对应的校验字段、并将没勾选的校验去除
      let vsl = {};
      val.forEach((element) => {
        vsl = {
          codeNumber: element.inventoryCode,
          quantity: element.applynumber,
          plannedDeliveryDate: element.applytime,
          itemRemark: element.applybz,
          fabricWidth: element.doorwidth,
          modelNumber: element.frbaicName,
        };
        this.verify.push(vsl);
      });
      console.log(this.verify);
      // scope.$index当前行数据在数组中的索引，勾选哪一行校验哪一行的必填项
    },
    /** 查询交易记录列表 */
    getList() {
      this.loading = true;
      const params = {
        ...this.queryParams,
        type: 2,
        startDate: this.createDateObj?.[0] || null,
        endDate: this.createDateObj?.[1] || null,
        buysumbitStartDate: this.buysumbitTimeObj?.[0] || null,
        buysumbitEndDate: this.buysumbitTimeObj?.[1] || null,
        financialBuysumbitStartDate:
          this.financialBuysumbitTimeObj?.[0] || null,
        financialBuysumbitEndDate: this.financialBuysumbitTimeObj?.[1] || null,
      };
      // delete params.createDateObj;
      listRecord(params).then((response) => {
        this.recordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 状态 0 默认 待采购审核 ,1 : 采购已审核, 待财务审核 , 2: 驳回 , 3: 财务审核
    sumbitapply(type) {
      if (!this.ids.length) {
        this.$message.error("请勾选要审核的内容");
        return;
      }
      // 只有相同的状态才可以审核
      if (
        this.selRow.every(
          (item) => item.itemStatus == this.selRow[0].itemStatus
        )
      ) {
        // 采购员-选择
        if (type) {
          this.$confirm("是否通过审核?", "提示", {
            confirmButtonText: "通过",
            cancelButtonText: "驳回",
            type: "warning",
            distinguishCancelAndClose: true,
            closeOnClickModal: false,
            cancelButtonClass: "b-cancelButton",
          })
            .then(() => {
              // 通过
              this.approvalRequest();
            })
            .catch((e) => {
              if (e == "cancel") {
                // 驳回false，通过true
                sumbitapply(this.ids, "false").then((res) => {
                  this.$modal.msgSuccess("审核成功");
                  this.getList();
                });
              }
            });
        } else {
          // 财务操作
          this.approvalRequest();
        }
      } else {
        this.$message.error("请勾选相同状态的单据");
      }
    },
    // 审核
    approvalRequest() {
      sumbitapply(this.ids, "true").then((res) => {
        this.$modal.msgSuccess("审核成功");
        this.getList();
      });
    },
    // 废弃
    sumbitapplys() {
      // let a=JSON.stringify(this.ids);
      // console.log(a.join(','))
      let ids = "18,19"; //JSON.stringify(this.ids);
      sumbitapplys(ids).then((response) => {
        this.$modal.msgSuccess("审核成功");
        this.open = false;
        this.getList();
      });
    },
    /** 新增按钮操作 */
    handleAddlc() {
      this.reset();
      this.openlc = true;
      this.title = "新增【零裁】";
      // { isShortage: 0 } 面料状态 零裁 已废弃
      getlistlc().then((response) => {
        var listArr = [];
        for (var i = 0; i < response.rows.length; i++) {
          var item = response.rows[i];
          var obj = {
            // codeNumber: item.codeNumber, //存货编码
            clientName: item.clientName, //客户
            modelNumber: item.modelNumber, //型号
            length: item.length,
            number: "", //库存编码
            quantity: "",
            plannedDeliveryDate: null,
            itemRemark: "",
            productionTaskId: item.productionTaskId,
            applynumber: item.length,
          };
          listArr.push(obj);
        }
        this.recordListlc = listArr;
        // this.totallc = response.total;
        this.loading = false;
      });
    },
    handleAddql() {
      this.reset();
      this.openql = true;
      this.title = "新增【欠料】";
      // { isShortage: 1 } 面料状态 欠料 已废弃
      getlistql().then((response) => {
        var listArr = [];
        for (var i = 0; i < response.rows.length; i++) {
          var item = response.rows[i];
          var obj = {
            codeNumber: item.codeNumber, //存货编码
            modelNumber: item.modelNumber, //型号
            length: item.length, //长度
            number: item.number, //库存编码
            quantity: "",
            plannedDeliveryDate: null,
            itemRemark: "",
          };
          listArr.push(obj);
        }
        this.recordListql = listArr;
        this.loading = false;
      });
    },
    handleAddkc() {
      this.reset();
      this.openkc = true;
      this.title = "新增【库存】";
      getlistkc({
        pageNum: 1,
        pageSize: 100,
        type: 2,
        isStockUp: 1,
        isbuy: 1,
      }).then((response) => {
        this.formData.recordListkc = response.rows;
        this.totalkc = response.total;
        this.loading = false;
      });
    },
    search() {
      getlistkc(this.kcParams).then((response) => {
        this.formData.recordListkc = response.rows;
        this.totalkc = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.openlc = false;
      this.openql = false;
      this.openkc = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        transactionRecordId: null,
        orderId: null,
        clientId: null,
        clientName: null,
        cashAccount: null,
        rebateAccount: null,
        otherAccount: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.createDateObj = [];
      this.buysumbitTimeObj = [];
      this.financialBuysumbitTimeObj = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      // console.log(selection)
      this.ids = selection.map((item) => item.purchaseOrderItemId);
      console.log(this.ids);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      this.selRow = selection;
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "statistic/export",
        {
          ...this.queryParams,
        },
        `record_${new Date().getTime()}.xlsx`
      );
    },
    // 删除按钮操作
    handledelete(row) {
      var that = this;
      this.$confirm("是否确认删除，此操作不可逆, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deletekc(row.purchaseOrderItemId).then((res) => {
          this.$modal.msgSuccess(res.msg || "删除成功");
          this.getList();
        });
      });
    },
    getSupplierData(vendorName = "") {
      listVendor({
        pageNum: 1,
        pageSize: 100,
        vendorName,
      }).then(({ rows }) => {
        this.supplierData = rows;
      });
    },
    changeSupplier(val) {
      var index = this.supplierData.findIndex((a) => a.vendorName == val);
      if (index != -1) {
        this.applylist[0].supplierId = this.supplierData[index].vendorId;
      }
    },
    getCreateDateTime() {
      var dateArr = [];
      var now = new Date();
      let year = now.getFullYear(); // 获取完整的年份(4位数字)
      let month = String(now.getMonth() + 1).padStart(2, "0"); // 月份是从0开始的，所以要加1
      let day = String(now.getDate()).padStart(2, "0");
      let yesterday = String(now.getDate() - 1).padStart(2, "0");
      dateArr = [
        `${year}-${month}-${yesterday} 00:00:00`,
        `${year}-${month}-${day} 23:59:59`,
      ];
      return dateArr;
    },
    openInventory(row, index, code) {
      this[code] = index;
      this.$nextTick(() => {
        if (code == "qlPopover") {
          this.$refs.qbInventory.getList(row.modelNumber);
        } else if (code == "kcPopover") {
          this.$refs.kcInventory.getList(row.name);
        } else {
          // this.$refs.tableInventory.getList(row.modelNumber);
        }
        this.$forceUpdate();
      });
    },
    opentableInventory(row) {
      this.tablePopover = true;
      this.$nextTick(() => {
        this.$refs.tableInventory.getList(row.modelNumber);
      });
    },
    openTaskOrder(row, type) {
      this.tableTaskType = type;
      this.searchVal = row.modelNumber;
      this.tableTaskOrder = true;

      this.$nextTick(() => {
        if (type == "lc") {
          this.$refs.TaskOrder.getList(row.productionTaskId);
        }
        if (type == "ql") {
          this.$refs.QLTaskOrder.getList();
        }
      });
    },
    handleSchedule() {
      if (this.selRow.length == 0) {
        this.$message.error("请勾选单据");
        return;
      }
      this.scheduleVisible = true;
      this.plandate = null;
    },
    async submitSchedule() {
      let promiseList = [];
      for (var i = 0; i < this.selRow.length; i++) {
        var item = this.selRow[i];
        var that = this;
        let promise = new Promise((resolve, reject) => {
          if (item.itemStatus == 7 || item.itemStatus == 0) {
            item.submissionTime = !!that.plandate
              ? that.dateFormats(that.plandate)
              : "";
            item.itemStatus = 0;
            updatekc(item)
              .then((res) => {
                resolve(res || "提交成功");
              })
              .catch((er) => {
                reject(er || "操作失败");
              });
          } else {
            reject("该状态下无法提交");
          }
        });
        promiseList.push(promise);
      }
      await Promise.all(promiseList)
        .then((res) => {
          // 等所有异步请求完成后执行
          this.$modal.msgSuccess(res.msg || "提交成功");
        })
        .catch((er) => {
          this.$message.error(er || "操作失败！");
        })
        .finally(() => {
          this.scheduleVisible = false;
          this.getList();
        });
    },
    dateFormats(dataStr) {
      if (!dataStr) {
        return;
      }
      var dt = new Date(dataStr);
      var y = dt.getFullYear();
      var m = (dt.getMonth() + 1).toString().padStart(2, "0");
      var d = dt.getDate().toString().padStart(2, "0");
      var hh = dt.getHours().toString().padStart(2, "0");
      var mm = dt.getMinutes().toString().padStart(2, "0");
      var ss = dt.getSeconds().toString().padStart(2, "0");
      return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
    },
  },
  filters: {
    dateFormat(dataStr) {
      if (!dataStr) {
        return;
      }
      var dt = new Date(dataStr);
      var y = dt.getFullYear();
      var m = (dt.getMonth() + 1).toString().padStart(2, "0");
      var d = dt.getDate().toString().padStart(2, "0");
      var hh = dt.getHours().toString().padStart(2, "0");
      var mm = dt.getMinutes().toString().padStart(2, "0");
      var ss = dt.getSeconds().toString().padStart(2, "0");
      // ${y}-
      return `${m}-${d} ${hh}:${mm}:${ss}`;
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep {
  .el-form-item__content {
    margin-left: 0px !important;
  }
  .el-form-item {
    margin-bottom: 0 !important;
  }
  .queryForm .el-form-item {
    margin-bottom: 20px !important;
  }
  // .queryForm .el-input__inner {
  //   width: 100% !important;
  // }
  .textunderline {
    text-decoration: underline;
    cursor: pointer;
  }
}
</style>
<style lang="scss">
.b-cancelButton {
  background: #fef0f0 !important;
  border-color: #fbc4c4 !important;
  color: #f56c6c !important;
}
</style>
